//获取页面上的canvas
const getCanvas = function(canvasId){
  const ctx = wx.createCanvasContext(canvasId, this);
  this.setData({
    ctx: ctx,
    ox: 0
  });
};
//清空画布
const clearCanvas = function(){
  const app = getApp();
  this.data.ctx.clearRect(0, 0, app.globalData.windowWidth, app.globalData.windowHeight);
  //
  this.data.ctx.setFillStyle('#fff');
  this.data.ctx.fillRect(0, 0, app.globalData.windowWidth, app.globalData.windowHeight);
  this.data.ctx.draw();
};
//文字需要多行显示时
const textByteLength = function (text, num) { // text为传入的文本  num为单行显示的字节长度
  let textArr = text.split('');
  let count = Math.ceil(textArr.length / num);
  let result = [];
  for (let i = 0; i < count; i++) {
    let tmpArr = [];
    for (var j = 0; j < num; j++) {
      if (!textArr.length) {
        break;
      }
      tmpArr.push(textArr.shift())
    }
    result.push(tmpArr.join(''));
  }
  return result;
};
//保存canvas图片到本地
const saveCanvasImg = function(src){
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: res => {
              console.log(res);
              console.log('授权成功')
              resolve();
            }
          })
        } else {
          resolve();
        }
      },
      fail: err => {
        console.log(err);
      }
    });
  }).then(() => {
    return new Promise((resolve,reject)=>{
      //保存图片???
      wx.saveImageToPhotosAlbum({
        filePath: src,
        success(res) {
          wx.showToast({
            title: '保存成功',
          });
          resolve();
        },
        fail() {
          wx.showToast({
            icon: 'none',
            title: '保存失败',
          });
          reject();
        }
      })
    });
  });
};
//
module.exports = {
  getCanvas,
  clearCanvas,
  textByteLength,
  saveCanvasImg
};